import getComponentRootDom from "./getComponentRootDom";
import Icon from '@/components/Icon';
import styles from './showMessage.module.less'
/**
 * 
 * @param {String} content 消息内容
 * @param {String} type 消息类型 info error warn sucess
 * @param {Number} duration 消息弹框多久消失，0为不消失
 * @param {DomHtml} container 消息在container弹出并且居中，不传默认在页面正中心
 */
export default function(config={}){
    const content = config.content || '';
    const type = config.type || 'info';
    const duration = config.duration || 2000;
    const container = config.container || document.body;
    const div = document.createElement('div');
    const iconDom = getComponentRootDom(Icon,{type});
    div.innerHTML = `<span class="${styles.icon}">${iconDom.outerHTML}</span>
    <div>${content}</div>`;
    //设置样式
    div.className=`${styles.message} ${styles['message-'+type]}`;
    //把生成的div加入到容器里
    if(!container){
        //如果没有容器
        container = document.body;
    }
    else{
        if(getComputedStyle(container).position ==='static'){
            container.style.position ='relative';
        }
    }
    container.append(div);
    //强行渲染触发重排
    div.clientHeight;
    div.style.transform='translate(-50%,-50%)';
    div.style.opacity = 1;
    setTimeout(() => {
        div.style.transform='translate(-50%,-50%) translateY(-15px)';
        div.style.opacity = 0;
        div.addEventListener('transitionend',()=>{
            div.remove();
            //如果有回调函数就运行
            config.callback&&config.callback();
        },{once:true})
    }, duration);
}